package qingke.blog.Servlet;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import qingke.blog.dao.BlogDao;
import qingke.blog.pojo.User;

/**
 * Servlet implementation class WriterServlet
 */
@WebServlet("/WriteServlet")
public class WriteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BlogDao bd =new BlogDao();
       
    public WriteServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String title =request.getParameter("title");
	
		String content=request.getParameter("content");

		String username=(String)request.getSession().getAttribute("username");
		
		User user=bd.login(username);
		Date date=new Date();
		String contentPath=user.getId()+"_"+title+"_"+date.getTime()+".txt";
		File file =new File("D:/eclipse/Blog/WebContent/article/"+contentPath);
		if(!file.exists()){
			file.createNewFile();
		}
		BufferedWriter bf =new BufferedWriter(new FileWriter(file));
		bf.write(content+"\r\n");
		bf.flush();
		bf.close();
		bd.writer(title,contentPath,date.getTime(),user.getId());
		
		response.getWriter().println("<script>alert('提交成功');window.location.href='index1.jsp';</script>");

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
